package com.chalmers.foa.gui.menus;

import java.util.Collections;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;

import com.chalmers.foa.R;
import com.codecarpet.fbconnect.FBLoginButton;
import com.codecarpet.fbconnect.FBRequest;
import com.codecarpet.fbconnect.FBSession;
import com.codecarpet.fbconnect.FBLoginButton.FBLoginButtonStyle;
import com.codecarpet.fbconnect.FBRequest.FBRequestDelegate;
import com.codecarpet.fbconnect.FBSession.FBSessionDelegate;

public class Settings extends PreferenceActivity {

	private static final String LOG = "FBConnect";

	// /////////////////////////////////////////////////////////////////////////////////////////////////
	// This application will not work until you enter your Facebook
	// application's API key here:

	private static final String API_KEY = "4da7d451077b85e35a4f237a8bd33bd4"; // "<YOUR API KEY>";
	// Enter either your API secret or a callback URL (as described in
	// documentation):
	private static final String API_SECRET = "d83584c718a2d03dab572a6fd96d3fa9"; // "<YOUR SECRET KEY>";

	// /////////////////////////////////////////////////////////////////////////////////////////////////

	private FBSession mSession;
	private FBLoginButton mLoginButton;
	private Handler mHandler;
	private CheckBoxPreference mCheckBoxPreference;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setResult(0);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// Forces
																				// landscape
																				// mode
		addPreferencesFromResource(R.xml.asettings);
		mCheckBoxPreference = (CheckBoxPreference) getPreferenceScreen()
				.findPreference("facebook");
	}

	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		super.onPreferenceTreeClick(preferenceScreen, preference);
		if (preference.getKey().equals("facebook")) {
			mHandler = new Handler();
			mSession = FBSession.getSessionForApplication_secret(API_KEY,
					API_SECRET, new FBSessionDelegateImpl());
			mLoginButton = new FBLoginButton(this);
			mLoginButton.setStyle(FBLoginButtonStyle.FBLoginButtonStyleWide);
			mLoginButton.setSession(mSession);
			mSession.resume(this);
			mCheckBoxPreference.setChecked(mSession.isConnected());
			mLoginButton.performClick();
		}
		return true;
	}

	@Override
	public void onBackPressed() {
		setResult(2);
		super.onBackPressed();
	}

	private void checkPermission() {
		String fql = "select publish_stream from permissions where uid == "
				+ String.valueOf(mSession.getUid());
		Map<String, String> params = Collections.singletonMap("query", fql);
		FBRequest.requestWithDelegate(new FBHasPermissionRD()).call(
				"facebook.fql.query", params);
	}

	private class FBSessionDelegateImpl extends FBSessionDelegate {

		@Override
		public void sessionDidLogin(FBSession session, Long uid) {
			// we check if the user already has the permissions before
			// displaying permission buttonv
			Log.v("Logged in", "");
			checkPermission();
			mHandler.post(new Runnable() {
				public void run() {
					mCheckBoxPreference.setChecked(true);
				}
			});

			String fql = "select uid,name from user where uid == "
					+ session.getUid();

			Map<String, String> params = Collections.singletonMap("query", fql);
			FBRequest.requestWithDelegate(new FBRequestDelegateImpl()).call(
					"facebook.fql.query", params);
		}

		@Override
		public void sessionDidLogout(FBSession session) {
			mHandler.post(new Runnable() {
				public void run() {
					if(!mSession.isConnected())
						mCheckBoxPreference.setChecked(false);
				}
			});
		}

	}


	private class FBRequestDelegateImpl extends FBRequestDelegate {

		@Override
		public void requestDidFailWithError(FBRequest request, Throwable error) {
			Log.v("Fail", "");
		}
	}

	private class FBHasPermissionRD extends FBRequestDelegate {

		@Override
		public void requestDidFailWithError(FBRequest request, Throwable error) {
			super.requestDidFailWithError(request, error);
		}

		@Override
		public void requestDidLoad(FBRequest request, Object result) {
			int hasPermission = 0;

			Log.v("requestDidLoad", "");
			if (result instanceof JSONArray) {
				JSONArray jsonArray = (JSONArray) result;
				try {
					JSONObject jo = jsonArray.getJSONObject(0);
					hasPermission = jo.getInt("publish_stream");
					if (hasPermission == 0) {
						mHandler.post(new Runnable() {
							public void run() {
							}
						});
					}
				} catch (JSONException e) {
					Log.e(LOG, "Permission response error", e);
				}
			}
		}
	}
}